#define _CRT_SECURE_NO_WARNINGS
#include"List.h"

ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail\n");
		return NULL;
	}
	newnode->_data = x;
	newnode->_next = NULL;
	newnode->_prev = NULL;
	return newnode;
}

bool LTEmpty(ListNode* pHead)
{
	assert(pHead);
	return pHead->_next == pHead;
}

ListNode* ListCreate()
{
	ListNode* phead = BuyListNode(-1);
	phead->_next = phead;
	phead->_prev = phead;
	return phead;
}

void ListDestory(ListNode* pHead)
{
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		ListNode* next = cur->_next;
		free(cur);
		cur = next;
	}
	free(pHead);
	pHead = NULL;
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	printf("graud<==>");
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		printf("%d <==>", cur->_data);
		cur = cur->_next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = BuyListNode(x);
	newnode->_next = pHead->_prev;
	pHead->_prev->_next = newnode;
	pHead->_prev = newnode;
	newnode->_next = pHead;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead); 
	assert(!LTEmpty(pHead));
	ListNode* tail = pHead->_prev;
	pHead->_prev = tail->_prev;
	pHead->_prev->_next = pHead;
	free(tail);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	assert(!LTEmpty(pHead));
	ListNode* newnode = BuyListNode(x);
	newnode->_next = pHead->_next;
	newnode->_prev = pHead;
	pHead->_next->_prev = newnode;
	pHead->_next = newnode;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!LTEmpty(pHead));
	ListNode* del = pHead->_next;
	pHead->_next = del->_next;
	pHead->_next->_prev = pHead;
	free(del);
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	assert(!LTEmpty(pHead));
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		if (cur->_data == x)
		{
			return cur;
		}
		cur = cur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	ListNode* newnode = BuyListNode(x);
	newnode->_prev = pos->_prev;
	pos->_prev->_next = newnode;
	newnode->_next = pos;
	pos->_prev = newndoe;
}

void ListErase(ListNode* pos)
{
	pos->_prev->_next = pos->_next;
	pos->_next->_prev = pos->_prev;
	free(pos);
}